<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="申请编号:" prop="purchaseApplyNo">
        <el-input v-model="queryParams.purchaseApplyNo" placeholder="请输入采购申请编号" clearable @keyup.enter="handleQuery" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="申请人:" prop="applyUserName">
        <el-input v-model="queryParams.applyUserName" placeholder="请输入申请人姓名" clearable @keyup.enter="handleQuery" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="申请部门:" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入申请部门名称" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="需求的时间:" prop="applyDate">
        <el-date-picker clearable v-model="queryParams.applyDate" type="date" placeholder="请选择需求的时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="status" style="width: 240px">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in purchase_apply_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['purchase:apply:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['purchase:apply:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applyList">
      <el-table-column label="申请编号" align="center" prop="purchaseApplyNo" width="300">
        <template #default="scope">
          <span @click="handleShowDetails(scope.row)" style="color: #1c84c6">{{scope.row.purchaseApplyNo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUserName" />
      <el-table-column label="申请部门" align="center" prop="deptName" />
      <el-table-column label="审核请人" align="center" prop="examineUserName" />
      <el-table-column label="需求的时间" align="center" prop="applyDate" width="180"/>
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="purchase_apply_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <!-- 根据 status 值显示不同按钮 -->
          <template v-if="scope.row.status === 0">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['purchase:apply:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['purchase:apply:remove']">删除</el-button>
            <el-button link type="primary" icon="link" @click="handleSubmit(scope.row)" v-hasPermi="['purchase:apply:submit']">提交</el-button>
          </template>
          <template v-else-if="scope.row.status === 1">
            <el-button v-if="isApprove(scope.row)" link type="primary" icon="CircleCheck" @click="handleApprove(scope.row)" v-hasPermi="['purchase:apply:approve']">申请通过</el-button>
            <el-button v-if="isApprove(scope.row)" link type="primary" icon="CircleClose" @click="handleReject(scope.row)" v-hasPermi="['purchase:apply:reject']">审核驳回</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改采购申请对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body style="width: 70%;height: 80%">
      <el-form ref="applyRef" :model="form" :rules="rules">
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="申请编号" prop="purchaseApplyNo" style="width: 300px" >
            <el-input v-model="form.purchaseApplyNo" placeholder="请输入采购申请编号" disabled />
          </el-form-item>
          <el-form-item label="申请人" prop="applyUserName">
            <el-input v-model="form.applyUserName" placeholder="请输入申请人" disabled/>
          </el-form-item>
          <el-form-item label="审核人" prop="examineUserId" >
            <el-select v-model="form.examineUserId" placeholder="请选择审核人" style="width: 180px">
              <el-option v-for="option in selectUserOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="需求的时间" prop="applyDate">
            <el-date-picker clearable v-model="form.applyDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择需求的时间">
            </el-date-picker>
          </el-form-item>
        </div>
        <div>
          <h2>采购申请清单</h2>
          <el-col :span="1.5" class="mb8">
            <el-button type="primary" plain icon="Plus" @click="handleAddMaterial">新增</el-button>
          </el-col>

          <el-table  style="height: 300px; overflow: auto;" :data="list">
            <el-table-column label="物料名称" align="center" prop="materialName" >
              <template #default="scope">
                <el-select
                    v-model="scope.row.materialId"
                    placeholder="Select"
                    size="large"
                    style="width: 240px"
                >
                  <el-option v-for="option in selectMaterialOptions" :key="option.value" :label="option.label" :value="option.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="purchaseApplyNumber" >
              <template #default="scope">
                <el-input-number v-model="scope.row.purchaseApplyNumber"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" v-if="!data.isAdding">
              <template #default="scope" >
                <el-button link type="primary" icon="Delete" @click="handleDeleteMaterial(scope.row)" v-hasPermi="['purchase:apply:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情页 -->
    <el-dialog :title="title" v-model="openA" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="applyRef" :model="form">
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="申请编号" prop="purchaseApplyNo" style="width: 300px" >
            <el-input v-model="form.purchaseApplyNo" placeholder="请输入采购申请编号" disabled />
          </el-form-item>
          <el-form-item label="申请人" prop="applyUserName">
            <el-input v-model="form.applyUserName" placeholder="请输入申请人" disabled/>
          </el-form-item>
          <el-form-item label="审核人" prop="examineUserId" >
            <el-input v-model="form.examineUserName" placeholder="请输入申请人" disabled/>
          </el-form-item>
          <el-form-item label="需求的时间" prop="applyDate">
            <el-input v-model="form.applyDate" placeholder="请输入申请人" disabled/>
          </el-form-item>
        </div>
        <div>
          <h2>采购申请清单</h2>

          <el-table  style="height: 400px; overflow: auto;" :data="list">
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="数量" align="center" prop="purchaseApplyNumber" />
            <el-table-column label="单位" align="center" prop="unitId">
              <template #default="scope">
                <dict-tag :options="unit_type" :value="scope.row.unitId" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Apply">
import {listApply, getApply, delApply, addApply, updateApply, changeStatus,getCGSQ,deleteByApplyId} from "@/api/purchase/apply/apply";
import { listUser } from "@/api/system/user";
import {listMaterials} from "@/api/base/materials.js";

import useUserStore from "../../../store/modules/user.js";
import { ElMessageBox } from 'element-plus';
import {delMaterial, listMaterial} from "../../../api/purchase/apply/apply.js";

const {proxy} = getCurrentInstance();
const {purchase_apply_status ,unit_type} = proxy.useDict('purchase_apply_status','unit_type');

const applyList = ref([]);
const open = ref(false);
const openA = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleMaterial = ref("")
const applyRowId = ref(null);


const data = reactive({
  form: {
    list: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    purchaseApplyNo: null,
    applyUserId: null,
    deptId: null,
    examineUserId: null,
    applyDate: null,
    status: null,
  },
  rules: {
    examineUserId: [
      {required: true, message: "审核人不能为空", trigger: "change"}
    ],
    applyDate: [
      {required: true, message: "需求的时间不能为空", trigger: "change"}
    ]
  }
});

//采购清单列表
const list = ref([])

const { queryParams, form, rules } = toRefs(data);

// 获取登录对象并获取其 id 值
let userId = useUserStore().id;
let userName = useUserStore().name;
// 设置查询参数中的 applyUserId 和 examineUserId
queryParams.value.applyUserId = userId;
queryParams.value.examineUserId = userId;

/** 查询采购申请列表 */
function getList() {
  loading.value = true;
  listApply(queryParams.value).then(response => {
    applyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

}

// 提交按钮操作函数
function handleSubmit(row) {
  ElMessageBox.confirm('是否确认提交？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 提交后状态变为 1
    row.status=1
    changeStatus(row.id,row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 申请通过按钮操作函数
function handleApprove(row) {
  ElMessageBox.confirm('是否确认申请通过？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 申请通过后状态变为 2
    row.status=2
    changeStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 审核驳回按钮操作函数
function handleReject(row) {
  ElMessageBox.confirm('是否确认审核驳回？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 审核驳回后状态变为 3
    row.status = 3
    changeStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    purchaseApplyNo: null,
    applyUserId: null,
    deptId: null,
    examineUserId: null,
    applyDate: null,
    status: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    isAdding: false,
  };
  proxy.resetForm("applyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 设置申请人id为登录用户的id
  list.value = []
  form.value.list = list;
  form.value.applyUserId = userId;
  form.value.applyUserName = userName;
  open.value = true;
  data.isAdding = true;
  title.value = "添加采购申请";
  getCGSQ().then(response => {
    form.value.purchaseApplyNo= response.msg
  })
  applyRowId.value = null;
}

const isApprove = (row) => {
  // 获取登录用户详细信息
  const loginUser = useUserStore().id;
  // 判断登录用户是否为审批人
  return row.examineUserId === loginUser;
};

// 新增：用于存储用户列表的ref
const userList = ref([]);
const materialsList = ref([]);

// 获取用户列表的函数
const getUsers = async () => {
  const response = await listUser();
  userList.value = response.rows;
  console.log(userList.value)
};

/** 查询物料管理列表 */
const getMaterialList = async () =>  {
  const response = await listMaterials();
  materialsList.value = response.rows
  console.log(materialsList.value)
}

// 在页面加载时获取用户列表、物料列表
onMounted(() => {
  getUsers();
  getMaterialList()
});
// 新增：计算属性，生成el - select选项
const selectUserOptions = computed(() => {
  return userList.value.map(user => ({ label: user.userName, value: user.userId }));
});
const selectMaterialOptions = computed(() => {
  return materialsList.value.map(material => ({ label: material.materialName, value: material.id }));
});

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getApply(_id).then(response => {
    form.value = response.data;
    console.log(response.data)
    list.value = response.data.list
    data.isAdding = false;
    open.value = true;
    title.value = "修改采购申请";
    // 设置被点击修改的行的id值
    applyRowId.value = row.id;
  });
}

/** 提交按钮  采购申请的提交按钮 */
function submitForm() {
  proxy.$refs["applyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateApply(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.list = list
        addApply(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购申请编号为"' + _ids + '"的数据项？').then(function () {
    return delApply(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}
// 删除采购申请的物料
function handleDeleteMaterial(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购申请编号为"' + _ids + '"的数据项？').then(function () {
    return delMaterial(_ids);
  }).then(() => {
    getList();
    form.value.list = list;
    proxy.$modal.msgSuccess("删除成功");
    getApply(form.value.id).then(response => {
      form.value = response.data;
      list.value = response.data.list;
    });
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchase/apply/export', {
    ...queryParams.value
  }, `apply_${new Date().getTime()}.xlsx`)
}

//新增采购申请清单
function handleAddMaterial(){
  let obj = {
    materialId: '',
    purchaseApplyNumber: '',
  }
  list.value.push(obj)
}
// 显示详情页
function handleShowDetails(row) {
  form.value = {...row };
  // 将采购申请列表数据赋值给详情页的列表数据
  list.value = row.list || [];
  openA.value = true;
  title.value = "采购申请详情";
}

getList();
</script>
